function ListNode(val, next) {
  this.val = val == undefined ? 0 : val;
  this.next = next == undefined ? null : next;
}

function createList(values) {
  let nodes = values.map((val) => new ListNode(val));
  for (let i = 0; i < nodes.length - 1; i++) {
    nodes[i].next = nodes[i + 1];
  }
  return nodes[0];
}

//打印链表
function printList(head) {
  let current = head;
  while (current) {
    console.log(current.val);
    current = current.next;
  }
}

let l1 = createList([9,9,9,9,9,9,9]);
let l2 = createList([9,9,9,9]);

let addTwoNumbers = function (l1, l2) {
  let dummy = new ListNode(0);
  let current = dummy
  let carry = 0
  while (l1 || l2 || carry) {
    let val1 = l1 ? l1.val : 0;
    let val2 = l2 ? l2.val : 0;

    let sum =  val1 + val2 + carry;
    carry = Math.floor(sum / 10);

    current.next = new ListNode(sum % 10);
    current = current.next;

    l1 = l1 ? l1.next : null;
    l2 = l2 ? l2.next : null;
  }
  return dummy.next;
};

let l3 = addTwoNumbers(l1, l2);
printList(l3);
